package com.cykj.page03;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page04
 * @Author: WWJ
 * @CreateTime: 2025-06-15 00:07
 * @Description:  动态获取静态资源
 * @Version: 1.0
 */
public class MySever {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9090);
        System.out.println("服务器启动成功，监听端口：9090");
        Socket socket = serverSocket.accept();

        while (true){

            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = inputStream.read(bytes);
            String request = new String(bytes, 0, len);
            System.out.println("客户端请求数据：\n" + request);

            MyHttpRequest httpRequest = new MyHttpRequest(request);
            String filePath ="webapps/static/images"+httpRequest.getRequestURL();
            File file = new File(filePath);
            if (httpRequest.getRequestURL().equals("/")){
                filePath = "webapps/pages/index.html";
            }else if (!file.exists()){
                filePath = "webapps/pages/404.html";
            }
            StaticResourceHandler staticResourceHandler = new StaticResourceHandler(filePath);
            //响应
            //获取输出流，用于发送响应数据给客户端（浏览器）
            OutputStream os = socket.getOutputStream();
            //下面是构造 HTTP 响应报文（3部分：响应行、响应头、响应体）
            //响应行
            os.write("HTTP/1.1 200 OK".getBytes());
            os.write("\r\n".getBytes());
            //响应头
            os.write(("Content-Type:"+staticResourceHandler.getMedia()+";charset=UTF-8").getBytes());
            os.write("\r\n".getBytes());
            os.write(("Content-Length:"+staticResourceHandler.getFileBytes().length).getBytes());// // 告诉浏览器图片有多大
            os.write("\r\n".getBytes());

            os.write("\r\n".getBytes());//// 空行，表示响应头结束，接下来是响应体
            //响应体
            os.write(staticResourceHandler.getFileBytes());
        }

    }
}
